package com.xbongbong.formula.qlexpress.operator.text;

import com.ql.util.express.Operator;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;

import java.util.Objects;

/**
 * @author: wufeng
 * @date: 2018/7/5 15:22
 * @desrcption: 将文本转化为数字。
 */
public class OperatorValue extends Operator {

    public OperatorValue(String name){
        this.name = name;
    }

    public OperatorValue(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }

    /**
     * @param list
     * list[0] 将文本转化为数字。
     * @return
     * @throws Exception
     */
    @Override
    public Object executeInner(Object[] list) throws Exception {

        if (Objects.isNull(list) || list.length != Constant.ONE) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        String value = list[0].toString();
        if (!RegexUtil.isNumber(value)) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        if (!value.contains(".")) {
            Long num = Long.valueOf(value);
            if (num <= Integer.MAX_VALUE && num> Integer.MIN_VALUE) {
                return Integer.valueOf(value);
            }
            return num;
        } else {
            return Double.valueOf(value);
        }

    }
}

